package lib.apache.http;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import java.io.*;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.security.KeyStore;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class HttpPostUtil {

    /**
     * 如果调用dmz转发的外网地址，需要先下载证书，导入jre中，
     * 详细参考https://blog.csdn.net/gabriel576282253/article/details/81531746/
     */

    public static void main(String[] args) throws Exception {

//        List<CathodicProtectionRate> rateList = new ArrayList<>();
//        CathodicProtectionRate rate = new CathodicProtectionRate();
//        rate.setCorrosionRateId("09");
//        rate.setCollectTime(new Date());
//        rate.setCorrosionRate(new BigDecimal(9));
//        rate.setDiffusionResistance(new BigDecimal(9));
//        rate.setTestblockThickness(new BigDecimal(9));
//        rate.setAccumulatedCorrosion(new BigDecimal(9));
//        rateList.add(rate);
//
//        CathodicProtectionRate rate1 = new CathodicProtectionRate();
//        rate1.setCorrosionRateId("08");
//        rate1.setCollectTime(new Date());
//        rate1.setCorrosionRate(new BigDecimal(8));
//        rate1.setDiffusionResistance(new BigDecimal(8));
//        rate1.setTestblockThickness(new BigDecimal(8));
//        rate1.setAccumulatedCorrosion(new BigDecimal(8));
//        rateList.add(rate1);

        String params = "[]";//JSONObject.toJSONString(rateList);
        // 类型 1为外网调用dmz；2为内网调用
        String type = "1";
        // token 外网调用固定为 “Y”; 内网待定
        String token = "Y";

        // url为接口地址
        String result = sslRequest("接口地址", params, token, type);
        System.out.println(result);
    }

    public static String sslRequest(String url, String params, String token, String type) throws Exception {
        String results = null;

        if (type.equals("1")) {
            // .p12文件在 本地的路径
            String PFX_PATH = "C:\\Users\\18811\\Desktop\\client.p12";
            // client.p12证书默认密码"123456"
            String PFX_PWD = "123456";
            KeyStore keyStore = KeyStore.getInstance("PKCS12");
            InputStream instream = new FileInputStream(new File(PFX_PATH));
            try {
                // 这里就指的是KeyStore库的密码
                keyStore.load(instream, PFX_PWD.toCharArray());
            } finally {
                instream.close();
            }
            SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, PFX_PWD.toCharArray()).build();
            SSLConnectionSocketFactory scsf = new SSLConnectionSocketFactory(sslcontext, NoopHostnameVerifier.INSTANCE);
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext
                    , new String[]{"TLSv1"}  // supportedProtocols ,这里可以按需要设置
                    , null  // supportedCipherSuites
                    , SSLConnectionSocketFactory.getDefaultHostnameVerifier());

            CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
            try {
                // post请求
                HttpPost httpPost = new HttpPost(url);
                httpPost.setHeader("FROM", token);
                httpPost.setEntity(new StringEntity(params, Consts.UTF_8));
                CloseableHttpResponse response = httpclient.execute(httpPost);

                try {
                    HttpEntity entity = response.getEntity();
                    // 返回结果
                    results = EntityUtils.toString(response.getEntity(), "UTF-8");
                    EntityUtils.consume(entity);
                    return results;
                } finally {
                    response.close();
                }
            } finally {
                httpclient.close();
            }
        }

        if (type.equals("2")) {
            StringBuffer sbf = new StringBuffer();
            String strRead;
            try {
                URL actionUrl = new URL(url);
                HttpURLConnection connection = (HttpURLConnection) actionUrl.openConnection();
                connection.setRequestMethod("POST");//请求post方式
                connection.setDoInput(true);
                connection.setDoOutput(true);
                //header内的的参数在这里set
                connection.setRequestProperty("Authorization", token);
                connection.setRequestProperty("TENANTID", "dc32482c91944f0e49b3560a2cb9913b");
                connection.setRequestProperty("Content-Type", "application/json");
                connection.connect();
                OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
                //body参数放这里
                writer.write(params);
                writer.flush();
                InputStream is = connection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                while ((strRead = reader.readLine()) != null) {
                    sbf.append(strRead);
                    sbf.append("\r\n");
                }
                reader.close();
                connection.disconnect();
                results = sbf.toString();
                return results;

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return results;
        }

        return results ;
    }


}
